import React, { Component } from 'react';
import './group.less';
import { meshLog, SPRemove, SPGet, SPSet } from "../../../config";
import PubSub from 'pubsub-js'
import {
    sumHexBytes, transIntToHex4Str, getOctets2Msg, transIntToHex2Str,
    bigEndianToLittleEndian
} from '../../../utils/dataUtils'
import {
    saveGroupInfor
} from '../../../utils/homeUtils'

class Group extends Component {

    constructor(props) {
        super(props);
        this.state = {
            isOn: true,
            cctLevel: 50,
            cctLevelValue: 1000,
            dimLevel: 50,
            groupInfo: '',
            cctModeArray: [],
            motionSensorEnabled: true,
            detectionArea: 'Medium',
            maxDim: '50%',
            holdTime: '150',
            standbyDim: '30%',
            standbyPeriod: '0s',
            daylightSensor: true,
            daylightThreshold: '200Lux',
            dhEnabled: false,

        }
    }

    componentDidMount() {
        meshLog('group渲染第一步', this.props);
        const groupList = JSON.parse(SPGet("groupList"))
        const groupInfo = groupList.find(item => item.groupID == this.props.groupInfo.groupID)
        const cctModeArray = groupInfo.cctModeArray
        const cctLevelValue = ((cctModeArray[cctModeArray.length - 1] - cctModeArray[0]) * (groupInfo.cctLevel) / 400) + cctModeArray[0]
        const motionModel = groupInfo.motionModel
        let detectionArea = ''
        if (motionModel.detectionSensitivity == 0) {
            detectionArea = 'Low'
        } else if (motionModel.detectionSensitivity == 1) {
            detectionArea = 'Medium'
        } else {
            detectionArea = 'High'
        }
        const daylightModel = groupInfo.daylightModel
        meshLog('groupInfo.isOnOff', groupInfo.isOnOff);

        this.setState({
            groupInfo: groupInfo,
            cctModeArray: cctModeArray,
            cctLevel: groupInfo.cctLevel,
            cctLevelValue: cctLevelValue,
            dimLevel: groupInfo.dimLevel,
            isOn: groupInfo.isOnOff,
            detectionArea: detectionArea,
            motionSensorEnabled: motionModel.isEnabled,
            holdTime: motionModel.holdTime + 's',
            maxDim: motionModel.maxLight + '%',
            standbyPeriod: motionModel.standbyPeriod + 's',
            standbyDim: motionModel.standbyDimLevel + '%',
            daylightSensor: daylightModel.isEnabled,
            daylightThreshold: daylightModel.threshold + 'Lux',
            dhEnabled: daylightModel.isDaylightHarvesting
            // groupDevices: groupDevices,
        })
    }

    handleToggle = (key) => {
        this.setState((prev) => ({ [key]: !prev[key] }));
        meshLog('key', key);
        meshLog(' 这边ID不应该是props的id中的，应该将切换组之后的id上传到数据库，然后从数据库中获取id，之后在获取组的所有信息', this.props.groupInfo.groupID);
        const wangguan = JSON.parse(SPGet("wangguan"))
        const groupList = JSON.parse(SPGet("groupList"))
        let groupInfo = groupList.find(item => item.groupID == this.props.groupInfo.groupID)
        const wangguanmac = bigEndianToLittleEndian(wangguan.macAddress)
        const groupID = this.props.groupInfo.groupID
        let data1 = '252517'
        let data
        let data2
        let data3
        if (key == 'isOn') {
            let date4 = groupInfo.isOnOff === true ? '00' : '01'
            let date5 = !groupInfo.isOnOff
            meshLog('date5', date5);
            data2 = '00006100000000000003' + getOctets2Msg(transIntToHex4Str(groupID)) + '0000000000640000' + '0110' + date4 + '0A' //64是100的亮度值
            data3 = sumHexBytes(data2) + '5252'
            data = '0,' + wangguanmac + ',' + data1 + data2 + data3 + ',';
            //修改localStorage上数据
            groupInfo.isOnOff = date5
            meshLog('groupInfo', groupInfo);
            const groupListAll = saveGroupInfor(groupInfo)
            meshLog('groupListAll', groupListAll);

        } else if (key == 'motionSensorEnabled') {
            let motionModel = groupInfo.motionModel
            let daylightModel = groupInfo.daylightModel
            let date4 = motionModel.isEnabled === true ? '00' : '01'
            let date5 = !motionModel.isEnabled
            let data6 = daylightModel.isEnabled === true ? '00' : '01'
            meshLog('date5', date5);
            data2 = '00006100000000000003' + getOctets2Msg(transIntToHex4Str(groupID)) + '0000000000640000' + '3110' + date4 + data6 //同时需要上传两个状态人感，光感
            data3 = sumHexBytes(data2) + '5252'
            data = '0,' + wangguanmac + ',' + data1 + data2 + data3 + ',';
            //修改localStorage上数据
            motionModel.isEnabled = date5
            meshLog('groupInfo', groupInfo);
            const groupListAll = saveGroupInfor(groupInfo)
            meshLog('groupListAll', groupListAll);

        } else if (key == 'daylightSensor') {
            let motionModel = groupInfo.motionModel
            let daylightModel = groupInfo.daylightModel
            let date4 = daylightModel.isEnabled === true ? '00' : '01'
            let date5 = !daylightModel.isEnabled
            let data6 = motionModel.isEnabled === true ? '00' : '01'
            meshLog('date5', date5);
            data2 = '00006100000000000003' + getOctets2Msg(transIntToHex4Str(groupID)) + '0000000000640000' + '3110' + data6 + date4  //同时需要上传两个状态人感，光感
            data3 = sumHexBytes(data2) + '5252'
            data = '0,' + wangguanmac + ',' + data1 + data2 + data3 + ',';
            //修改localStorage上数据
            daylightModel.isEnabled = date5
            meshLog('groupInfo', groupInfo);
            const groupListAll = saveGroupInfor(groupInfo)
            meshLog('groupListAll', groupListAll);
        } else if (key == 'dhEnabled') {
            let motionModel = groupInfo.motionModel
            let daylightModel = groupInfo.daylightModel
            let date4 = daylightModel.isDaylightHarvesting === true ? '00' : '01'
            let date5 = !daylightModel.isEnabled
            data1 = '252516'
            meshLog('date5', date5);
            data2 = '00006100000000000003' + getOctets2Msg(transIntToHex4Str(groupID)) + '0000000000640000' + 'A110' + date4  //同时需要上传两个状态人感，光感
            data3 = sumHexBytes(data2) + '5252'
            data = '0,' + wangguanmac + ',' + data1 + data2 + data3 + ',';
            //修改localStorage上数据
            daylightModel.isDaylightHarvesting = date5
            meshLog('groupInfo', groupInfo);
            const groupListAll = saveGroupInfor(groupInfo)
            meshLog('groupListAll', groupListAll);
        }


        PubSub.publish('showUpdate', data)//控制mqtt发信息
    };

    handleChange = (key, value) => {
        this.setState({ [key]: value });
        meshLog('key', key, value);
        const wangguan = JSON.parse(SPGet("wangguan"))
        const groupList = JSON.parse(SPGet("groupList"))
        let groupInfo = groupList.find(item => item.groupID == this.props.groupInfo.groupID)
        const wangguanmac = bigEndianToLittleEndian(wangguan.macAddress)
        const groupID = this.props.groupInfo.groupID
        let data1
        let data
        let data2
        let data3
        if (key == 'dimLevel') {
            meshLog('value', value);
            data1 = '252517'
            data2 = '00006100000000000003' + getOctets2Msg(transIntToHex4Str(groupID)) + '0000000000640000' + '1110' + (transIntToHex2Str(value)) + '0A' //64是100的亮度值
            data3 = sumHexBytes(data2) + '5252'
            data = '0,' + wangguanmac + ',' + data1 + data2 + data3 + ',';
            //修改localStorage上数据
            groupInfo.dimLevel = value
            //meshLog('groupInfo', groupInfo);
            const groupListAll = saveGroupInfor(groupInfo)
            meshLog('groupListAll', groupListAll);
        } else if (key == 'cctLevel') {
            meshLog('value', value);
            const cctModeArray = groupInfo.cctModeArray
            const cctLevelValue = Math.round(((cctModeArray[cctModeArray.length - 1] - cctModeArray[0]) * (value) / 400) + cctModeArray[0])
            this.setState({ cctLevelValue: cctLevelValue });
            data1 = '252518'
            data2 = '00006100000000000003' + getOctets2Msg(transIntToHex4Str(groupID)) + '0000000000640000' + '2110' + getOctets2Msg(transIntToHex4Str(value)) + '0A' //色温
            data3 = sumHexBytes(data2) + '5252'
            data = '0,' + wangguanmac + ',' + data1 + data2 + data3 + ',';
            //修改localStorage上数据
            groupInfo.cctLevel = value
            //meshLog('groupInfo', groupInfo);
            const groupListAll = saveGroupInfor(groupInfo)
            meshLog('groupListAll', groupListAll);

        } else if (key == 'cctLevelValue') {
            meshLog('value', value);
            const cctModeArray = groupInfo.cctModeArray
            const cctLevel = Math.round(((value - cctModeArray[0]) / (cctModeArray[cctModeArray.length - 1] - cctModeArray[0]) * 400))
            data1 = '252518'
            data2 = '00006100000000000003' + getOctets2Msg(transIntToHex4Str(groupID)) + '0000000000640000' + '2110' + getOctets2Msg(transIntToHex4Str(cctLevel)) + '0A' //色温
            data3 = sumHexBytes(data2) + '5252'
            data = '0,' + wangguanmac + ',' + data1 + data2 + data3 + ',';
            //修改localStorage上数据
            groupInfo.cctLevel = cctLevel
            //meshLog('groupInfo', groupInfo);
            const groupListAll = saveGroupInfor(groupInfo)
            meshLog('groupListAll', groupListAll);
            this.setState({ cctLevel: cctLevel });
        } else if (key == 'detectionArea') {
            let motionModel = groupInfo.motionModel
            let detectionSensitivity = 0
            if (value == 'Low') {
                detectionSensitivity = 0
            } else if (value == 'Medium') {
                detectionSensitivity = 1
            } else {
                detectionSensitivity = 2
            }

            data1 = '252516'
            data2 = '00006100000000000003' + getOctets2Msg(transIntToHex4Str(groupID)) + '0000000000640000' + '4110' + (transIntToHex2Str(detectionSensitivity))  //色温
            data3 = sumHexBytes(data2) + '5252'
            data = '0,' + wangguanmac + ',' + data1 + data2 + data3 + ',';
            //修改localStorage上数据
            motionModel.detectionSensitivity = detectionSensitivity
            //meshLog('groupInfo', groupInfo);
            const groupListAll = saveGroupInfor(groupInfo)
            meshLog('groupListAll', groupListAll);

        } else if (key == 'maxDim') {
            let motionModel = groupInfo.motionModel
            let maxLight = parseInt(value.replace("%", ""))
            //meshLog('maxLight', maxLight);
            data1 = '252516'
            data2 = '00006100000000000003' + getOctets2Msg(transIntToHex4Str(groupID)) + '0000000000640000' + '5110' + (transIntToHex2Str(maxLight))  //色温
            data3 = sumHexBytes(data2) + '5252'
            data = '0,' + wangguanmac + ',' + data1 + data2 + data3 + ',';
            //修改localStorage上数据
            motionModel.maxLight = maxLight
            //meshLog('groupInfo', groupInfo);
            const groupListAll = saveGroupInfor(groupInfo)
            meshLog('groupListAll', groupListAll);
        } else if (key == 'holdTime') {
            let motionModel = groupInfo.motionModel
            let holdTime = parseInt(value.replace("s", ""))
            meshLog('holdTime', holdTime);
            data1 = '252517'
            data2 = '00006100000000000003' + getOctets2Msg(transIntToHex4Str(groupID)) + '0000000000640000' + '6110' + getOctets2Msg(transIntToHex4Str(holdTime))  //色温
            data3 = sumHexBytes(data2) + '5252'
            data = '0,' + wangguanmac + ',' + data1 + data2 + data3 + ',';
            //修改localStorage上数据
            motionModel.holdTime = holdTime
            //meshLog('groupInfo', groupInfo);
            const groupListAll = saveGroupInfor(groupInfo)
            meshLog('groupListAll', groupListAll);

        } else if (key == 'standbyDim') {
            let motionModel = groupInfo.motionModel
            let standbyDim = parseInt(value.replace("%", ""))
            //meshLog('maxLight', maxLight);
            data1 = '252516'
            data2 = '00006100000000000003' + getOctets2Msg(transIntToHex4Str(groupID)) + '0000000000640000' + '7110' + (transIntToHex2Str(standbyDim))  //色温
            data3 = sumHexBytes(data2) + '5252'
            data = '0,' + wangguanmac + ',' + data1 + data2 + data3 + ',';
            //修改localStorage上数据
            motionModel.standbyDim = standbyDim
            //meshLog('groupInfo', groupInfo);
            const groupListAll = saveGroupInfor(groupInfo)
            meshLog('groupListAll', groupListAll);
        } else if (key == 'standbyPeriod') {
            let motionModel = groupInfo.motionModel
            let standbyPeriod = parseInt(value.replace("s", ""))
            meshLog('standbyPeriod', standbyPeriod);
            data1 = '252516'
            data2 = '00006100000000000003' + getOctets2Msg(transIntToHex4Str(groupID)) + '00000000000000' + '8110' + getOctets2Msg(transIntToHex4Str(standbyPeriod))  //色温
            data3 = sumHexBytes(data2) + '5252'
            data = '0,' + wangguanmac + ',' + data1 + data2 + data3 + ',';
            //修改localStorage上数据
            motionModel.standbyPeriod = standbyPeriod
            //meshLog('groupInfo', groupInfo);
            const groupListAll = saveGroupInfor(groupInfo)
            meshLog('groupListAll', groupListAll);

        } else if (key == 'daylightThreshold') {
            let motionModel = groupInfo.motionModel
            let daylightThreshold = parseInt(value.substring(0, 3))
            meshLog('daylightThreshold', daylightThreshold);
            data1 = '252517'
            data2 = '00006100000000000003' + getOctets2Msg(transIntToHex4Str(groupID)) + '0000000000640000' + '8110' + getOctets2Msg(transIntToHex4Str(daylightThreshold))  //色温
            data3 = sumHexBytes(data2) + '5252'
            data = '0,' + wangguanmac + ',' + data1 + data2 + data3 + ',';
            //修改localStorage上数据
            motionModel.daylightThreshold = daylightThreshold
            //meshLog('groupInfo', groupInfo);
            const groupListAll = saveGroupInfor(groupInfo)
            meshLog('groupListAll', groupListAll);

        }
        PubSub.publish('showUpdate', data)//控制mqtt发信息0210
    };

    render() {
        const {
            isOn,
            cctLevel,
            motionSensorEnabled,
            detectionArea,
            maxDim,
            holdTime,
            standbyDim,
            standbyPeriod,
            daylightSensor,
            daylightThreshold,
            dhEnabled,
            groupInfo,
            cctModeArray,
            dimLevel,
            cctLevelValue
        } = this.state;

        return (
            <div className="home-container">
                {/* 第一行：组名和电源按钮 */}
                <div className="group-header">
                    <div className="group-name">{groupInfo.name}</div>
                    <div className={`power-icon ${isOn ? 'on' : 'off'}`} onClick={() => this.handleToggle('isOn')}></div>
                </div>

                {/* 第二行：Dim Level */}
                <div className="dim-level">
                    <div className="label">Dim level</div>
                    <div className="value-boxes">
                        <div className="box blue">0W</div>
                        <div className="box">{dimLevel}%</div>
                    </div>

                </div>
                {/* 第四行：Dim滑动条 */}
                <input
                    type="range"
                    min="0"
                    max="100"
                    value={dimLevel}
                    className="slider"
                    onChange={(e) => this.handleChange('dimLevel', parseInt(e.target.value))}
                />

                {/* 第三行：CCT Tunable */}
                {/* <div className="dim-level">CCT Tunable</div> */}

                <div className="dim-level">
                    <div className="label">CCT level</div>
                    <div className="value-boxes">
                        {/* <div className="box blue">0W</div> */}
                        <div className="box">{cctLevelValue}k</div>
                    </div>

                </div>

                {/* 第四行：滑动条 */}
                <input
                    type="range"
                    min="0"
                    max="400"
                    value={cctLevel}
                    className="slider"
                    onChange={(e) => this.handleChange('cctLevel', parseInt(e.target.value))}
                />

                {/* 第五行：四个按钮 */}
                <div className="cct-buttons">
                    {cctModeArray.map((val) => (
                        <button
                            key={val}
                            className={`cct-btn ${cctLevelValue === val ? 'active' : ''}`}
                            onClick={() => this.handleChange('cctLevelValue', val)} >
                            {val + 'k'}
                        </button>
                    ))}
                </div>

                {/* Motion Sensor 部分 */}
                <div className="motion-section">
                    <div className="motion-header">
                        <span>Motion sensor</span>
                        <div className="motion-icon" />
                        <label className="switch">
                            <input type="checkbox" checked={motionSensorEnabled} onChange={() => this.handleToggle('motionSensorEnabled')} />
                            <span className="slider-round"></span>
                        </label>
                    </div>

                    {motionSensorEnabled && (
                        <div className="motion-settings">
                            <div className="setting-item">
                                <label>Detection Area</label>
                                <select value={detectionArea} onChange={(e) => this.handleChange('detectionArea', e.target.value)}>
                                    <option>Low</option>
                                    <option>Medium</option>
                                    <option>High</option>
                                </select>
                            </div>

                            <div className="setting-item">
                                <label>Max Dim</label>
                                <select value={maxDim} onChange={(e) => this.handleChange('maxDim', e.target.value)}>
                                    <option>10%</option>
                                    <option>20%</option>
                                    <option>30%</option>
                                    <option>40%</option>
                                    <option>50%</option>
                                    <option>60%</option>
                                    <option>70%</option>
                                    <option>80%</option>
                                    <option>90%</option>
                                    <option>100%</option>
                                </select>
                            </div>

                            <div className="setting-item">
                                <label>Holdtime</label>
                                <select value={holdTime} onChange={(e) => this.handleChange('holdTime', e.target.value)}>
                                    <option>180s</option>
                                    <option>300s</option>
                                    <option>600s</option>
                                    <option>900s</option>
                                </select>
                            </div>

                            <div className="setting-item">
                                <label>Standby Dim Level</label>
                                <select value={standbyDim} onChange={(e) => this.handleChange('standbyDim', e.target.value)}>
                                    <option>10%</option>
                                    <option>20%</option>
                                    <option>30%</option>
                                    <option>40%</option>
                                    <option>50%</option>
                                    <option>60%</option>
                                    <option>70%</option>
                                    <option>80%</option>
                                    <option>90%</option>
                                    <option>100%</option>
                                </select>
                            </div>

                            <div className="setting-item">
                                <label>Standby Period</label>
                                <select value={standbyPeriod} onChange={(e) => this.handleChange('standbyPeriod', e.target.value)}>
                                    <option>0s</option>
                                    <option>300s</option>
                                    <option>600s</option>
                                </select>
                            </div>
                        </div>
                    )}
                </div>

                {/* Daylight Sensor */}
                <div className="daylight-section">

                    <div className="daylight-header">
                        <span>Daylight Sensor</span>
                        <label className="switch">
                            <input type="checkbox" checked={daylightSensor} onChange={() => this.handleToggle('daylightSensor')} />
                            <span className="slider-round"></span>
                        </label>
                    </div>
                    {daylightSensor && (
                        <div className="motion-settings">
                            <div className="setting-item">
                                <label>Daylight Threshold</label>
                                <select value={daylightThreshold} onChange={(e) => this.handleChange('daylightThreshold', e.target.value)}>
                                    <option>100Lux</option>
                                    <option>200Lux</option>
                                    <option>300Lux</option>
                                </select>

                            </div>

                            {/* DH 开关 */}
                            <div className="dh-section">
                                <div className="daylight-header">
                                    <span>DH</span>
                                    <label className="switch">
                                        <input type="checkbox" checked={dhEnabled} onChange={() => this.handleToggle('dhEnabled')} />
                                        <span className="slider-round"></span>
                                    </label>
                                </div>
                            </div>
                        </div>

                    )}
                </div>


            </div>
        );
    }
}

export default Group;
